package com.cxyzy.listviewdemo;

import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView

class ListViewAdapter(var context: Context) : BaseAdapter() {
    private var mDataList = mutableListOf<String>()

    /**
     * 设置数据
     */
    fun setData(dataList: List<String>) {
        mDataList.clear()
        mDataList.addAll(dataList)
        //数据变更后，需要调用notifyDataSetChanged通知数据变化。
        notifyDataSetChanged()
    }

    override fun getView(position: Int, convertView: View?, viewGroup: ViewGroup?): View {
        var viewHolder: ViewHolder
        var view: View
        //下面对convertView进行判断，是为了复用已存在的视图，提升效率。
        if (convertView == null) {
            view = View.inflate(context, R.layout.item_layout, null);
            viewHolder = ViewHolder(view)
            view.tag = viewHolder
        } else {
            view = convertView
            viewHolder = view.tag as ViewHolder
        }
        //获取当前位置数据
        val item = getItem(position)
        //显示用户名
        if (item is String) {
            viewHolder.nameTv.text = item
        }
        return view
    }

    override fun getItem(position: Int): Any {
        return mDataList[position]
    }

    override fun getItemId(position: Int): Long {
        return 0
    }

    override fun getCount(): Int {
        return mDataList.size
    }

    class ViewHolder(view: View) {
        var nameTv: TextView = view.findViewById(R.id.nameTv)
    }
}